package com.tenglong.teacher.ui.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.content.Context.CONNECTIVITY_SERVICE;


public class AppVersionUpdate {

    static String downloadurl;

    public static void showUpdataDialog(final Context mContext, String url) {
    	downloadurl=url;
        AlertDialog.Builder builer = new AlertDialog.Builder(mContext);
        builer.setTitle("版本升级");
        builer.setMessage(isNetWorkConnect(mContext)+"系统检测到新版本 \n是否更新？");
        builer.setPositiveButton("确定", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                downLoadApk(mContext);
                
            }
        });
        builer.setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

    public static String isNetWorkConnect(Context context){
        ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
        if (null == networkInfo)
        {

        }else{
            NetworkInfo.State state = connectMgr.getNetworkInfo(
                    ConnectivityManager.TYPE_MOBILE).getState();
            if (NetworkInfo.State.CONNECTED == state){
                return "当前的网络处于移动网络环境下";
            }

        }
        return "";
    }
    private static void downLoadApk(final Context mContext) {
        boolean haveInstallPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                AlertDialog.Builder builer = new AlertDialog.Builder(mContext);
                builer.setTitle("版本升级");
                builer.setMessage("安装应用需要打开未知来源权限，请去设置中开启权限");
                builer.setPositiveButton("确定", new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            startInstallPermissionSettingActivity(mContext);
                        }

                    }
                });
                builer.setNegativeButton("取消", new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builer.create();
                dialog.show();

                return;
            }
        }
        final ProgressDialog pd;
        pd = new ProgressDialog(mContext);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                       pd.dismiss();

                    }
                });
        pd.show();
        new Thread() {

            @Override
            public void run() {
                try {

                    File file = getFileFromServer(downloadurl, pd);
                    sleep(3000);
                    installApk(file,mContext);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            pd.setMax(conn.getContentLength());
            float all = (float) (conn.getContentLength()/1024.00/1024); 
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "3zmy_update.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                float percent = (float)(total/1024.00/1024);
                if(!pd.isShowing()){
                    return null;
                }
                pd.setProgress(total);
                pd.setProgressNumberFormat(String.format("%.2fM/%.2fM", percent, all));
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else {
            return null;
        }
    }

    private static void startInstallPermissionSettingActivity(Context mContext) {
        Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        ((Activity) mContext).startActivityForResult(intent,10086);
    }
    protected static void installApk(File file, Context mContext) {
        if(file==null){
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(mContext, "net.cuotibao.fileprovider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
